var async = require('async');
var RsDownloader = require('./RsDownloader');
var J2I = require("./json2image");
var I2V = require('./image2video');
var urlparse = require('url').parse;
var config = require('./config');
var path = require('path');
var fs = require('fs');

var startTime = new Date().getTime();
async.waterfall([
	//1.得到参数，并返回链接给下一步

	function(cb) {
		process.argv.forEach(function (val, index, array) {
			var key = val.split("=")[0];
			if(key == 'videoPath'){
				var linkPath = val.split("=")[1];
				cb(null,linkPath);
			}else if(array.length == (index - 1)){
				cb(new Error("required parameter missing:videoPath"));
			}
		});
	},
	//2.下载链接中的资源到临时文件夹
	function(linkPath,cb) {
		var urlInfo = urlparse(linkPath);
		var protocol = urlInfo.protocol;
		if(protocol == 'http:'){
			var rsDownloader = new RsDownloader(linkPath);
			rsDownloader.downloadRs(function(err){
				config.originPath = path.join(config.tmpPath, 'originData');
				cb(err);
			});
		}else if(protocol == 'file:'){
			config.originPath = linkPath.substring(6,linkPath.length);
			cb();
		}

	},
	//3.获取基本信息赋值到config
	function(cb){
		fs.readFile(config.originPath + "/event.json",{encoding:'utf-8'}, function (err,result) {
			if(err)
				cb(err);
			else{
				var jsonData = JSON.parse(result);
				if(jsonData.info.canvasHeight !== 0)
					config.screenHeight = jsonData.info.canvasHeight;
				if(jsonData.info.canvasWidth !== 0)
					config.screenWidth = jsonData.info.canvasWidth;
				cb();
			}
		});
	},
	//4.转换成图片
	function(cb) {
		console.log('Download resource success:::');
		J2I.convert(cb);
	},
	//5.转换成视频
	function(cb){
		console.log('Convert to image success:::');
		I2V.convert(function(err){
			cb(err);
		});
	}
], function(err, values) {
	console.log('总共用时：'+(new Date().getTime() - startTime)/1000 + '秒');
	if(err){
		console.error(err.message);
	}else
		console.log('convert success!!');
});